<template>
  <div class="users-section">
    <div class="table-container">
      <el-table
        :data="paginatedUserlist"
        style="width: 100%"
        :max-height="500"
        @selection-change="handleSelectionChange"
      >
        <el-table-column prop="id" label="ID" min-width="80" align="center" />
        <el-table-column prop="openid" label="微信openid" min-width="120" />
        <el-table-column prop="unionid" label="微信unionid" min-width="140" />
        <el-table-column prop="nickname" label="用户昵称" min-width="120" />
        <el-table-column prop="avatar" label="头像" min-width="100">
          <template #default="{ row }">
            <img
              :src="getAvatarUrl(row.avatar)"
              alt="头像"
              style="
                width: 60px;
                height: 60px;
                border-radius: 50%;
                object-fit: cover;
              "
              @error="handleImageError"
            />
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? "正常" : "封禁" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdTime"
          label="创建时间"
          min-width="180"
          :formatter="formatDateTime"
        />
        <el-table-column
          prop="updatedTime"
          label="最后登录时间"
          min-width="180"
          :formatter="formatDateTime"
        />
        <el-table-column label="操作" min-width="120" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                size="small"
                type="primary"
                @click="handleEditUser(row)"
                plain
                class="action-btn"
                >编辑</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 编辑框 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户" width="500px">
      <el-form :model="editForm" label-width="100px">

        <el-form-item label="状态">
          <div style="display: flex; gap: 20px">
            <el-button
              :type="editForm.status == 0 ? 'danger' : 'default'"
              @click="setStatus(0)"
              plain
              style="flex: 1"
            >
              封禁
            </el-button>
            <el-button
              :type="editForm.status == 1 ? 'success' : 'default'"
              @click="setStatus(1)"
              plain
              style="flex: 1"
            >
              正常
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSave()">保存</el-button>
      </template>
    </el-dialog>

    <!-- 积分调整对话框 -->
    <el-dialog
      v-model="balanceAdjustDialogVisible"
      title="调整用户积分"
      width="400px"
    >
      <el-form :model="balanceAdjustForm" label-width="80px">
        <el-form-item label="当前积分">
          <el-input v-model="editForm.balance" disabled />
        </el-form-item>
        <el-form-item label="调整类型">
          <el-radio-group v-model="balanceAdjustForm.type">
            <el-radio label="add">增加</el-radio>
            <el-radio label="subtract">减少</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调整数量">
          <el-input-number
            v-model="balanceAdjustForm.amount"
            :min="1"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="balanceAdjustForm.remark" placeholder="调整原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="balanceAdjustDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBalanceAdjust"
          >确认调整</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.action-buttons {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.action-btn {
  width: 80px !important;
  height: 32px !important;
  font-size: 12px !important;
  padding: 0 !important;
  margin: 0 !important;
}

.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
  background: #fff;
  border-radius: 8px;
  margin-top: 16px;
  box-shadow: 0 2px 8px rgba(25, 118, 210, 0.1);
}
</style>

<script setup>
import { ref, reactive, computed, watch } from "vue";

import { ElMessage, ElMessageBox } from "element-plus";
import usersapi from "../api/usersapi";

const emit = defineEmits(["updateUserList"]);

// 响应式数据声明
const editDialogVisible = ref(false);
const balanceAdjustDialogVisible = ref(false);

const editForm = reactive({
  id: "",
  openid: "",
  unionid: "",
  nickname: "",
  avatar: "",
  balance: "",
  memberType: "",
  memberExpireTime: "",
  status: "",
  createdTime: "",
  updatedTime: "",
});


const balanceAdjustForm = reactive({
  type: "add", // add 或 subtract
  amount: 0,
  remark: "",
});

const props = defineProps({
  userlist: {
    type: Array,
    required: true,
  },
});

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(20);
const selectedRows = ref([]);

// 计算分页后的数据
const paginatedUserlist = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return props.userlist.slice(start, end);
});

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 监听数据变化，重置分页
watch(
  () => props.userlist,
  () => {
    currentPage.value = 1;
  },
  { deep: true }
);

// 获取头像URL，添加域名前缀
const getAvatarUrl = (avatar) => {
  if (!avatar || avatar === "" || avatar === "null" || avatar === "undefined") {
    // 返回默认头像
    return "";
  }

  // 如果已经是完整的URL（包含http或https），直接返回
  if (avatar.startsWith("http://") || avatar.startsWith("https://")) {
    return avatar;
  }

  // 添加域名前缀
  const baseUrl = "http://tool_back.connectsphere.top";
  return baseUrl + (avatar.startsWith("/") ? avatar : "/" + avatar);
};

// 处理图片加载错误
const handleImageError = (event) => {
  // 设置默认头像
  event.target.src =
    "";
};

// 编辑用户
const handleEditUser = (user) => {
  Object.assign(editForm, user);
  editDialogVisible.value = true;
};

// 格式化时间
const formatDateTime = (row, column, cellValue) => {
  if (!cellValue) return "-";

  try {
    // 如果已经是Date对象或时间戳
    const date = new Date(cellValue);
    if (isNaN(date.getTime())) {
      // 尝试处理字符串格式
      if (typeof cellValue === "string") {
        // 处理可能的不同时间格式
        const parsedDate = new Date(cellValue.replace(/-/g, "/"));
        if (!isNaN(parsedDate.getTime())) {
          return formatDate(parsedDate);
        }
      }
      return cellValue; // 无法解析则返回原值
    }
    return formatDate(date);
  } catch (e) {
    console.error("格式化时间出错:", e);
    return cellValue;
  }
};

// 辅助格式化函数
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 查看用户积分明细
const viewUserBalance = (user) => {
  selectedUserOpenid.value = user.openid;
  balanceDialogVisible.value = true;
};

// 查看用户使用记录
const viewUserUsage = (user) => {
  selectedUserOpenid.value = user.openid;
  usageDialogVisible.value = true;
};

// 删除用户
const handleDeleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.nickname}" 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await usersapi.getdelete(user.id);
    ElMessage.success("删除成功");
    emit("updateUserList");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除用户失败:", error);
      ElMessage.error("删除用户失败");
    }
  }
};

// 打开积分调整对话框
const openBalanceAdjustDialog = () => {
  balanceAdjustForm.amount = editForm.balance;
  balanceAdjustForm.remark = "";
  balanceAdjustDialogVisible.value = true;
};

// 确认调整积分
const confirmBalanceAdjust = () => {
  // 计算新积分
  let newBalance = parseInt(editForm.balance) || 0;
  if (balanceAdjustForm.type === "add") {
    newBalance += parseInt(balanceAdjustForm.amount) || 0;
  } else {
    newBalance -= parseInt(balanceAdjustForm.amount) || 0;
  }
  editForm.balance = newBalance;
  balanceAdjustDialogVisible.value = false;
  ElMessage.success("积分调整成功");
};

// 设置用户状态
const setStatus = (status) => {
  editForm.status = status;
};

// 图片上传处理方法
const handleAvatarChange = async (option) => {
  const file = option.file;
  const formData = new FormData();
  formData.append("file", file);

  try {
    // 第一步：上传图片到OSS
    const uploadRes = await usersapi.getupdateALY(formData);
    const ossUrl = uploadRes.data.data || uploadRes.data;
    console.log("上传成功:", ossUrl);

    if (!ossUrl) {
      throw new Error("上传返回地址为空");
    }

    if (!editForm.id) {
      throw new Error("用户ID不存在");
    }

    // 第二步：更新数据库
    const updateData = {
      avatar: ossUrl,
      id: editForm.id,
    };
    await usersapi.getupdateImg(updateData);

    // 更新本地 editForm 数据
    editForm.avatar = ossUrl;
    ElMessage.success("头像更新成功");
    option.onSuccess && option.onSuccess(uploadRes.data, file);
  } catch (e) {
    console.error("上传失败:", e);
    ElMessage.error(
      "头像更新失败: " + (e.response?.data?.message || e.message || "未知错误")
    );
    option.onError && option.onError(e);
  }
};

// 修改用户数据
const handleEditSave = async () => {
  try {
    console.log('准备提交的数据:', editForm); // 添加调试
    const response = await usersapi.getupdate(editForm);
    console.log('API响应:', response.data); // 添加调试
    
    emit('updateUserList');
    editDialogVisible.value = false;
    ElMessage.success("保存成功");
  } catch (e) {
    console.error("保存失败:", e);
    ElMessage.error("保存失败: " + (e.response?.data?.message || e.message));
  }
};
</script>

<style scoped>
.balance-field {
  display: flex;
  align-items: center;
}

.balance-input {
  flex: 1;
}

.balance-input :deep(.el-input__wrapper) {
  background-color: #f5f7fa;
  font-weight: bold;
  font-size: 16px;
  color: #409eff;
}

.balance-input :deep(.el-input__inner) {
  background-color: transparent;
  font-weight: bold;
  font-size: 16px;
  color: #409eff;
  text-align: center;
}

.balance-input :deep(.el-input__suffix) {
  display: flex;
  align-items: center;
}
</style>